package com.flats.model.dao.hibernate;

import com.flats.model.entity.Flat;
import com.flats.model.entity.Persistent;
import com.flats.model.entity.Users;
import org.hibernate.SQLQuery;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Transactional
public class FlatHibernateDao<T extends Persistent> extends AbstractHibernateDao<Flat> {
    @Override
    @Transactional
    public Serializable saveOrUpdate(Flat persistent) {
        getSession().beginTransaction();
        Serializable id = getSession().save(persistent);
        getSession().getTransaction().commit();
        return id;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        getSession();
        getSession().beginTransaction();
        String query = "delete from ROOT_USER.FLAT where FLAT_ID =" + id.toString();
        SQLQuery sqlQuery = getSession().createSQLQuery(query);
        sqlQuery.executeUpdate();
        getSession().getTransaction().commit();
    }

    @Override
    @Transactional
    public void delete(Flat persistent) {
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        getSession().getTransaction().commit();
    }

    @Override
    @Transactional(readOnly = true)
    public Flat get(Long id) {
//        getSession();
//        getSession().beginTransaction();

        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
        Flat result = (Flat) getSession().load(Flat.class, id);
//        getSession().getTransaction().commit();
        return result;
    }

    @Override
    @Transactional (readOnly = true)
    public List<Flat> getAll() {
        if (!getSession().getTransaction().isActive()) {
            getSession().beginTransaction();
        }
//        getSession().beginTransaction();
        String query = "select * from ROOT_USER.FLAT";
        List<Flat> flatList = getSession().createSQLQuery(query)
                .addEntity(Flat.class)
                .list();
//        getSession().getTransaction().;
        return flatList;
    }
}
